/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="main-patternstatus">
    <!-- 环模式true -->
    <div
      style="overflow: hidden"
      v-if="this.contrloType === 'ring' || !this.contrloType"
    >
      <div
        class="ring-first"
        v-for="(list, index1) in patternInfo"
        :key="index1"
      >
        <draggable :move="move" :disabled="!cycles" :list="list">
          <!-- Number(item.greenWidth.replace('%', ''))+Number(item.flashgreen.replace('%', ''))+Number(item.yellowWidth.replace('%', ''))+Number(item.redWidth.replace('%', ''))+'%' -->
          <div
            style="position: relative"
            :style="{
              height: '34px',
              float: 'left',
              width:
                ((item.split + (item.sum ? item.sum : 0)) /
                  (max ? max : item.cycle)) *
                  100 +
                '%',
            }"
            v-for="(item, index2) in list"
            :key="index2"
            :class="item.mode === 7 ? 'direction' : ''"
          >
            <div
              :class="item.mode === 8 ? 'mask' : ''"
              class="first-1"
              :style="{
                width:
                  (Number(item.greenWidth.replace('%', '')) /
                    Number(
                      (
                        ((item.split + (item.sum ? item.sum : 0)) /
                          (max ? max : item.cycle)) *
                          100 +
                        '%'
                      ).replace('%', '')
                    )) *
                    100 +
                  '%',
                height: '34px',
                background: '#7ccc66',
              }"
            >
              <el-tooltip placement="top-start" effect="light">
                <div slot="content">P{{ item.id }}:{{ item.split }}</div>
                <div style="cursor: pointer">
                  <div class="ring-phase">
                    <!-- <PatternWalkSvg :showWalk="item.peddirection" :Width="'32'" :Height="'34'"></PatternWalkSvg> -->
                    <xdrdirselector
                      Width="38px"
                      Height="36px"
                      :showlist="item.direction"
                    ></xdrdirselector>
                  </div>
                  <div
                    class="box"
                    style="position: absolute; left: 35px; top: -1px"
                  >
                    <div class="ring-nums">P{{ item.id }}</div>
                    <!-- <div class="ring-nums">{{item.split}}</div> -->
                    <el-input-number
                      :disabled="!cycles"
                      class="ring-nums"
                      size="small"
                      :controls="false"
                      :min="0"
                      :step="1"
                      v-model.number="item.split"
                      @change="handleEdit(item)"
                      style="width: 24px"
                    ></el-input-number>
                  </div>
                </div>
              </el-tooltip>
              <div
                style="position: relative; width: 50px"
                v-for="(bus, index3) in busPhaseData"
                :key="index3"
              >
                <i
                  class="iconfont icon-lukouzhilu"
                  style="
                    position: absolute;
                    top: 8px;
                    left: 70px;
                    font-size: 12px;
                    color: #454545;
                  "
                  v-if="bus.controltype === 1 && bus.phaseid === item.id"
                ></i>
                <i
                  class="iconfont icon-BRT"
                  style="
                    position: absolute;
                    top: 8px;
                    left: 70px;
                    font-size: 12px;
                    color: #454545;
                  "
                  v-if="bus.controltype === 4 && bus.phaseid === item.id"
                ></i>
                <i
                  class="iconfont icon-xuxiangwei-xin"
                  style="
                    position: absolute;
                    top: 8px;
                    left: 70px;
                    font-size: 12px;
                    color: #454545;
                  "
                  v-if="bus.controltype === 99 && bus.phaseid === item.id"
                ></i>
                <i
                  class="iconfont icon-feijidongche"
                  style="
                    position: absolute;
                    top: 8px;
                    left: 70px;
                    font-size: 12px;
                    color: #454545;
                  "
                  v-if="bus.controltype === 6 && bus.phaseid === item.id"
                ></i>
                <i
                  class="iconfont icon-gongjiaoche"
                  style="
                    position: absolute;
                    top: 8px;
                    left: 70px;
                    font-size: 12px;
                    color: #454545;
                  "
                  v-if="bus.controltype === 3 && bus.phaseid === item.id"
                ></i>
                <i
                  class="iconfont icon-youguidianche"
                  style="
                    position: absolute;
                    top: 8px;
                    left: 70px;
                    font-size: 12px;
                    color: #454545;
                  "
                  v-if="bus.controltype === 5 && bus.phaseid === item.id"
                ></i>
              </div>
            </div>
            <div
              :class="item.mode === 8 ? 'mask' : ''"
              class="first-1"
              :style="{
                width:
                  (Number(item.flashgreen.replace('%', '')) /
                    Number(
                      (
                        (
                          ((item.split + (item.sum ? item.sum : 0)) /
                            (max ? max : item.cycle)) *
                          100
                        ).toFixed(3) + '%'
                      ).replace('%', '')
                    )) *
                    100 +
                  '%',
                height: '34px',
                float: 'left',
                background: 'linear-gradient(to right, #ffffff 50%, #7ccc66 0)',
                'background-size': '4px 100%',
              }"
            ></div>
            <div
              :class="item.mode === 8 ? 'mask' : ''"
              class="first-1"
              :style="{
                width:
                  (Number(item.yellowWidth.replace('%', '')) /
                    Number(
                      (
                        ((item.split + (item.sum ? item.sum : 0)) /
                          (max ? max : item.cycle)) *
                          100 +
                        '%'
                      ).replace('%', '')
                    )) *
                    100 +
                  '%',
                height: '34px',
                background: '#f9dc6a',
              }"
            ></div>
            <div
              :class="item.mode === 8 ? 'mask' : ''"
              class="first-1"
              :style="{
                width:
                  (Number(item.redWidth.replace('%', '')) /
                    Number(
                      (
                        (
                          ((item.split + (item.sum ? item.sum : 0)) /
                            (max ? max : item.cycle)) *
                          100
                        ).toFixed(3) + '%'
                      ).replace('%', '')
                    )) *
                    100 +
                  '%',
                height: '34px',
                background: '#f27979',
              }"
            ></div>
            <!-- (Math.round((100-Number(item.yellowWidth.replace('%', ''))/Number((((item.split+(item.sum?item.sum:0)) / (max?max:item.cycle) * 100).toFixed(3) + '%').replace('%', ''))*100-Number(item.flashgreen.replace('%', ''))/Number((((item.split+(item.sum?item.sum:0)) / (max?max:item.cycle) * 100).toFixed(3) + '%').replace('%', ''))*100-Number(item.greenWidth.replace('%', ''))/Number((((item.split+(item.sum?item.sum:0)) / (max?max:item.cycle) * 100).toFixed(3) + '%').replace('%', ''))*100)*100))/100 -->
          </div>
        </draggable>
      </div>
      <div v-if="showBarrier">
        <div v-for="(item, index) in barrierList" :key="index + '1'">
          <div
            class="divider"
            :style="{ left: item, height: barrierHeight }"
          ></div>
        </div>
      </div>
      <div
        v-show="
          (syncTime && cycle && cycle > 0) ||
          (syncTime && newCycle && newCycle > 0)
        "
      >
        <div
          class="curTimeDiv"
          :style="{ left: paddingLeft, 'background-color': '#299BCC' }"
        >
          {{ timeNumDevide }}
        </div>
        <div
          class="curTimeLine"
          :style="{ left: paddingLeft, height: barrierHeight }"
        ></div>
      </div>
    </div>
    <div v-if="this.contrloType === 'stage'">
      <div v-for="(list, index1) in stageLists" :key="index1">
        <!-- <div> -->
        <div
          class="first-1"
          :style="{
            width: list.greenWidth,
            position: 'relative',
            height: '34px',
            background: '#7ccc66',
          }"
        >
          <el-tooltip placement="top-start" effect="light">
            <div slot="content">
              <span
                class="ring-nums"
                v-for="(pha, index) in list.phases"
                :key="index"
              >
                P{{ pha }}
              </span>
            </div>
            <div style="cursor: pointer">
              <div class="ring-phase">
                <!-- <PatternWalkSvg :showWalk="list.peddirection" :Width="'32'" :Height="'34'"></PatternWalkSvg> -->
                <xdrdirselector
                  Width="36px"
                  Height="34px"
                  :showlist="list.direction"
                ></xdrdirselector>
              </div>
              <div
                class="box"
                style="position: absolute; left: 41px; top: -1px"
              >
                <div class="ring-nums">S{{ list.key + 1 }}</div>
                <div class="ring-nums">{{ list.stageSplit }}</div>
              </div>
              <!-- <div class="box" style="line-height:28px">
                      <span class="ring-nums" v-for="(pha,index) in list.phases" :key="index">
                    P:{{pha}}
                      </span>
                    </div> -->
            </div>
          </el-tooltip>
        </div>
        <!-- <div class="first-1" :style="{'width':item.flashgreen,'height':'34px','float':'left','background': 'linear-gradient(to right, #ffffff 50%, #7ccc66 0)','background-size': '4px 100%'}"></div> -->
        <div
          class="first-1"
          :style="{
            width: list.yellowWidth,
            height: '34px',
            background: '#f9dc6a',
          }"
        ></div>
        <div
          class="first-1"
          :style="{
            width: list.redWidth,
            height: '34px',
            background: '#f27979',
          }"
        ></div>
      </div>
    </div>
    <!-- </div> -->
  </div>
</template>
<script>
import xdrdirselector from '@/components/XRDDirSelector'
import draggable from 'vuedraggable'
// import patternwalksvg from '@/components/PatternWalkSvg/index'
// import PatternWalkSvg from 'openatc-components/package/kisscomps/components/PatternWalkSvg'
// import BusMapSvg from '../IntersectionMap/crossDirection/busIcon/busMapSvg'
import PhaseDataModel from 'openatc-components/package/kisscomps/components/IntersectionMap/crossDirection/utils'
import CrossDiagramMgr from '@/EdgeMgr/controller/crossDiagramMgr'
// import { getIntersectionInfo } from '@/api/template'
// import { getMessageByCode } from '@/utils/responseMessage'
// import { queryDevice } from '@/api/control'
export default {
  name: 'patternstatus',
  components: {
    // PatternWalkSvg,
    draggable,
    xdrdirselector
  },
  data () {
    return {
      barrierHeight: '',
      barrierList: [],
      newCycle: this.cycles,
      patternIds: this.patternId,
      newPatterns: [],
      newList: [],
      contrloCycle: 0,
      barrierArr: [],
      sidewalkPhaseData: [],
      // controlDatas: this.controlData,
      max: '',
      stageLists: [],
      busPhaseData: [], // 公交相位数据
      patternInfo: []
    }
  },
  props: {
    cycleChange: {
      type: Boolean,
      default: false
    },
    stagesChange: {
      type: Array
    },
    showBarrier: {
      type: Boolean,
      default: false
    },
    contrloType: {
      type: String
    },
    index: {
      type: Number
    },
    showCondition: {
      type: Boolean,
      default: false
    },
    phaseList: {
      type: Array
    },
    patternList: {
      type: Array
    },
    localPatternList: {
      type: Array
    },
    controlData: {
      type: Object
    },
    cycle: {
      type: Number
    },
    agentId: {
      type: String
    },
    cycles: {
      type: Number
    },
    patternId: {
      type: Number
    },
    patternStatusList: {
      type: Array
    },
    syncTime: {
      type: Number
    }
  },
  computed: {
    paddingLeft () {
      let res = '0%'
      if (this.contrloCycle > 0) {
        let curPercent = (this.contrloCycle - this.syncTime) / (this.max ? this.max : this.contrloCycle)
        res = curPercent * 100 + '%'
      }
      return res
    },
    timeNumDevide () {
      if (this.contrloCycle > 0) {
        let res = (this.contrloCycle - this.syncTime) + '/' + this.contrloCycle
        return res
      }
    }
  },
  watch: {
    controlData: {
      handler: function (val, oldVal) {
        if (this.contrloType === 'stage') {
          this.getIndexStage()
        }
        if (this.localPatternList) {
          this.max = ''
          let idPattern = this.localPatternList.filter(item => item.id === this.controlData.patternid)
          if (idPattern.length === 0 || (this.controlData && this.showCondition)) {
            this.handleTentivePatternData()
          } else {
            this.handlePatternData()
          }
          this.handleBarrierHeight()
        }
        // this.controlDatas = this.controlData
      },
      // 深度观察监听
      deep: true
    },
    cycleChange: {
      handler: function (val, oldVal) {
        this.handleCurrentChange(this.patternStatusList)
        this.handleBarrierHeight()
      },
      // 深度观察监听
      deep: true
    },
    phaseList: {
      handler: function (val, oldVal) {
        this.getPedPhasePos()
        this.getBusPos()
        this.getStage()
      },
      // 深度观察监听
      deep: true
    },
    agentId: {
      handler: function (val, oldVal) {
        this.getBusPos()
      },
      // 深度观察监听
      deep: true
    },
    patternId: {
      handler: function (val, oldVal) {
        this.patternIds = this.patternId
      },
      // 深度观察监听
      deep: true
    },
    cycles: {
      handler: function (val, oldVal) {
        this.newCycle = this.cycles
      },
      // 深度观察监听
      deep: true
    },
    contrloType: {
      handler: function (val, oldVal) {
        if (this.contrloType === 'stage') {
          this.getStage()
        }
      },
      // 深度观察监听
      deep: true
    },
    stagesChange: {
      handler: function (val, oldVal) {
        if (this.contrloType === 'stage') {
          this.getStage()
        }
      },
      // 深度观察监听
      deep: true
    },
    patternStatusList: {
      handler: function (val, oldVal) {
        this.handleBarrierHeight() // 计算屏障高度
        if (this.patternStatusList && this.newCycle) {
          setTimeout(() => {
            this.handleCurrentChange(this.patternStatusList)
          }, 10)
          this.handleBarrierHeight()
        }
      },
      // 深度观察监听
      deep: true
    }
  },
  created () {
    this.globalParamModel = this.$store.getters.globalParamModel
    if (this.patternStatusList && this.newCycle && !this.controlData) {
      setTimeout(() => {
        this.handleCurrentChange(this.patternStatusList)
        this.handleBarrierHeight()
      }, 400)
    }
    // 周期等比例切换
    // if (this.cycleChange) {
    //   const globalParamModel = this.$store.getters.globalParamModel
    //   let pattern = globalParamModel.getParamsByType('patternList')
    //   const allCycle = pattern.map(item => item.cycle)
    //   let cycle = Math.max(...allCycle)
    //   // setTimeout(() => {
    //   this.cycleEqualChange(this.patternStatusList, cycle)
    //   // }, 10)
    //   this.handleBarrierHeight()
    // }
    this.PhaseDataModel = new PhaseDataModel()
    this.CrossDiagramMgr = new CrossDiagramMgr()
    this.getPedPhasePos()
    this.getBusPos()
    if (this.contrloType === 'stage') {
      this.getStage()
    }
  },
  methods: {
    move (e) {
      // 这里的e表示即将停靠的元素。
      let result = this.barrierArr.filter(item => item.includes(e.relatedContext.element.id))[0]
      if (!result.includes(e.draggedContext.element.id)) {
        return false
      }
    },
    getPed (data) {
      let ped = []
      for (let stg of data) {
        let peddirections = []
        let currPhase = this.phaseList.filter((item) => {
          return item.id === stg
        })[0]
        if (!currPhase) return
        if (!currPhase.peddirection) return
        for (let walk of this.sidewalkPhaseData) {
          for (let ped of currPhase.peddirection) {
            let objs = {}
            objs.name = walk.name
            objs.id = walk.id
            if (ped === walk.id) {
              peddirections.push(objs)
              peddirections = Array.from(new Set(peddirections))
            }
          }
        }
        ped.push(...peddirections)
      }
      return ped
    },
    handleEdit (val) {
      this.patternStatusList.map(d => {
        d.map(r => {
          if (r.id === val.id) {
            r.value = val.split
          }
        })
      })
      let n = this.index
      const globalParamModel = this.$store.getters.globalParamModel
      let pattern = globalParamModel.getParamsByType('patternList')[n]
      globalParamModel.getParamsByType('patternList')[n].cycle = this.getMaxCycle(pattern)
    },
    getMaxCycle (pattern) {
      let modeId = pattern.stages.filter(item => item.length === 1)[0]
      let rings = pattern.rings
      let maxCycle = 0
      for (let ring of rings) {
        if (ring.length === 0) continue
        let cycle = 0
        for (let r of ring) {
          if (r.mode === 7 && (modeId && modeId[0] === r.id)) { // 忽略相位不计周期
            continue
          }
          cycle = cycle + r.value
        }
        if (cycle > maxCycle) {
          maxCycle = cycle
        }
      }
      return maxCycle
    },
    handleStageData (data) {
      if (!data) return
      let peddirections = this.getPed(data)
      let stagesTemp = []
      let tempList = []
      for (let stg of data) {
        let directionList = []
        let currPhase = this.phaseList.filter((item) => {
          return item.id === stg
        })[0]
        if (currPhase !== undefined) {
          directionList.push(...currPhase.direction)
          directionList = Array.from(new Set(directionList))
        }
        if (directionList.length === 0) {
          tempList.push({
            id: '',
            color: '#454545',
            peddirection: peddirections
          })
        } else {
          tempList = directionList.map(dir => ({
            id: dir,
            color: '#454545',
            peddirection: peddirections
          }))
        }
        let newTemp = tempList.filter(item => item.id !== '')
        stagesTemp.push(...newTemp)
      }
      return stagesTemp
    },
    getIndexStage () {
      if (this.localPatternList.length === 0) return
      for (let i = 0; i < this.localPatternList.length; i++) {
        if (this.controlData.patternid === this.localPatternList[i].id) {
          if (!this.localPatternList[i].stagesList) return
          let stageCycleList = this.localPatternList[i].stagesList.map(item => {
            return item.stageSplit ? item.stageSplit : 0
          })
          let stageMaxCyle = stageCycleList.reduce((a, b) => {
            return a + b
          }, 0)
          this.stageLists = this.localPatternList[i].stagesList.map(item => {
            return {
              ...item,
              // peddirection: this.getPed(item.phases ? item.phases : item.stages),
              direction: this.handleStageData(item.phases),
              greenWidth: (item.green / stageMaxCyle * 100).toFixed(3) + '%',
              yellowWidth: (item.yellow / stageMaxCyle * 100).toFixed(3) + '%',
              redWidth: (item.red / stageMaxCyle * 100).toFixed(3) + '%'
            }
          })
        }
      }
    },
    getStage () {
      if (!this.stagesChange) return
      let stageCycleList = this.stagesChange.map(item => {
        return item.stageSplit ? item.stageSplit : 0
      })
      let stageMaxCyle = stageCycleList.reduce((a, b) => {
        return a + b
      }, 0)
      if (this.cycleChange) {
        stageMaxCyle = this.max
      }
      this.stageLists = this.stagesChange.map(item => {
        return {
          ...item,
          // peddirection: this.getPed(item.phases ? item.phases : item.stages),
          direction: this.handleStageData(item.phases),
          greenWidth: ((item.stageSplit - item.yellow - item.red) / stageMaxCyle * 100).toFixed(3) + '%',
          yellowWidth: (item.yellow / stageMaxCyle * 100).toFixed(3) + '%',
          redWidth: (item.red / stageMaxCyle * 100).toFixed(3) + '%'
        }
      })
    },
    getBusPos () {
      // 公交相位信息
      this.busPhaseData = []
      this.phaseList.forEach((ele, i) => {
        // if (ele.controltype >= 3 && ele.controltype <= 5) {
        // ele.direction.forEach((dir, index) => {
        // 车道相位
        this.busPhaseData.push({
          phaseid: ele.id, // 相位id，用于对应相位状态
          // id: dir, // 接口返回的dir字段，对应前端定义的相位方向id，唯一标识
          // name: this.PhaseDataModel.getBusPhasePos(dir).name,
          controltype: ele.controltype
        })
        // })
        // }
      })
      let result = []
      let obj = {}
      for (var i = 0; i < this.busPhaseData.length; i++) {
        if (!obj[this.busPhaseData[i].phaseid]) {
          result.push(this.busPhaseData[i])
          obj[this.busPhaseData[i].phaseid] = true
        }
      }
      this.busPhaseData = result
    },
    getPedPhasePos () {
      // 行人相位信息
      this.sidewalkPhaseData = []
      this.phaseList.forEach((ele, i) => {
        if (ele.peddirection) {
          ele.peddirection.forEach((dir, index) => {
            // 行人相位
            if (this.PhaseDataModel.getSidePos(dir)) {
              this.sidewalkPhaseData.push({
                key: this.CrossDiagramMgr.getUniqueKey('pedphase'),
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir,
                name: this.PhaseDataModel.getSidePos(dir).name
              })
            }
          })
        }
      })
    },
    // 109临时方案根据controlData数据展示图形，其他的根据方案参数查数据图形
    handleTentivePatternData () {
      if (!this.controlData) return
      this.newList = []
      if (Object.keys(this.controlData).length === 0 || this.phaseList.length === 0) return
      if (!this.controlData.phase) return
      // let cycle = this.controlData.cycle
      if (!this.controlData.rings) return
      let newValue = []
      for (let rings of this.controlData.rings) {
        let phase = this.controlData.phase
        // let list = []
        let obj = {}
        for (let key in rings.sequence) {
          obj[key] = rings.sequence[key]
        }
        let newObj = Object.keys(obj).map(val => ({
          id: obj[val]
        }))
        newValue.push(newObj)
        for (let sequ of rings.sequence) {
          let obj = {}
          obj.id = sequ
          let split = phase.filter((item) => {
            return item.id === sequ
          })[0].split
          newValue.map(d => {
            d.map(r => {
              if (r.id === sequ) {
                r.value = split
              }
            })
          })
        }
      }
      this.handleTentative(newValue)
    },
    handlePatternData () {
      if (!this.controlData) return
      // this.newList = []
      if (Object.keys(this.controlData).length === 0 || this.phaseList.length === 0) return
      if (!this.controlData.phase) return
      if (!this.controlData.rings) return
      // let cycle = this.controlData.cycle
      let nowPattern = this.localPatternList.filter(item => {
        return item.id === this.controlData.patternid
      })[0].rings
      let filterPattern = []
      for (let i of nowPattern) {
        for (let j of this.controlData.rings) {
          let filterSequence = i.filter(item => j.sequence.includes(item.id))
          if (filterSequence.length > 0) {
            filterPattern.push(filterSequence)
          }
        }
      }
      for (let rings of this.controlData.rings) {
        for (let sequ of rings.sequence) {
          let split = this.controlData.phase.filter((item) => {
            return item.id === sequ
          })[0].split
          filterPattern.map(d => {
            return d.map(r => {
              if (r.id === sequ) {
                r.value = split
              }
            })
          })
        }
      }
      this.handleOverViewChange(filterPattern)
    },
    handleBarrierHeight () { // 屏障高度
      if (!this.patternInfo) return
      let patternLength = this.patternInfo.length
      this.barrierHeight = (patternLength * 35 + 21) + 'px'
    },
    handleTentative (val) {
      if (val === null || val.length === 0) return
      let valSplit = val.map(item => {
        return item.map(val => {
          return val.value + (val.sum ? val.sum : 0)
        })
      })
      let splitCycle = valSplit.length > 0 ? valSplit.map(item => {
        return item.length > 0 ? item.reduce((a, b) => {
          return a + b
        }) : 0
      }) : 0
      let cycle = Math.max(...splitCycle)// 每个环的周期最大值
      this.contrloCycle = cycle
      this.patternInfo = []
      let currentArr = []
      let newPattern = []
      val.map(i => {
        newPattern.push(...i)
      })
      if (this.phaseList.length === 0) return
      for (let patternStatus of val[0]) {
        if (patternStatus.mode !== 7) {
          let concurrent = this.phaseList.filter((item) => {
            return item.id === patternStatus.id // patternStatus.id当前相位id concurrent当前相位的并发相位
          })[0].concurrent// 当前相位的并发相位
          if (concurrent) {
            let obj = {
              id: patternStatus.id,
              current: concurrent.sort()
            }
            currentArr.push(obj)
          }
        }
      }
      if (currentArr.length !== 0) {
        let newCurrent = this.tranform(currentArr)
        let ringTeam = this.step1(this.phaseList, newCurrent)
        this.fillGap(ringTeam, val)
      }
      // let cycle = this.controlData.cycle
      for (let rings of val) {
        if (rings.length === 0) continue
        let list = []
        for (let ring of rings) {
          if (ring.value === 0) continue
          let obj = {}
          let split = ring.value
          obj.id = ring.id
          // obj.split = split
          let currPhase = this.phaseList.filter((item) => {
            if (item.id === ring.id && item.controltype === 99) {
              obj.controltype = item.controltype
            }
            return item.id === ring.id
          })[0]
          if (!currPhase) return
          let peddirections = []
          for (let walk of this.sidewalkPhaseData) {
            if (currPhase.peddirection) {
              for (let ped of currPhase.peddirection) {
                // if (stg === walk.phaseid) {
                let objs = {}
                objs.name = walk.name
                objs.id = walk.id
                if (ped === walk.id) {
                  peddirections.push(objs)
                  peddirections = Array.from(new Set(peddirections))
                }
                // }
              }
            } else {
              peddirections = []
            }
          }
          if (ring.desc) {
            obj.direction = ring.desc.map(item => { // 虚相位desc为空
              return {
                id: item.id,
                color: '#454545'
              }
            })
          } else {
            if (currPhase.direction && currPhase.direction.length > 0) {
              obj.direction = currPhase.direction.map(item => {
                return {
                  id: item,
                  peddirection: peddirections,
                  color: '#454545'
                }
              })
            } else {
              obj.direction = [
                {
                  id: '',
                  color: '#454545',
                  peddirection: peddirections
                }
              ]
            }
          }
          obj.split = split
          obj.cycle = cycle
          if (ring.sum) {
            obj.sum = ring.sum
            obj.redWidth = ((currPhase.redclear + ring.sum) / (this.max ? this.max : cycle) * 100) + '%'
          } else {
            obj.redWidth = (currPhase.redclear / (this.max ? this.max : cycle) * 100) + '%'
          }
          obj.flashgreen = (currPhase.flashgreen / (this.max ? this.max : cycle) * 100) + '%'
          obj.yellowWidth = (currPhase.yellow / (this.max ? this.max : cycle) * 100) + '%'
          obj.greenWidth = ((split - currPhase.redclear - currPhase.yellow - currPhase.flashgreen) / (this.max ? this.max : cycle) * 100) + '%'
          // 忽略相位不显示
          let mode = ring.mode
          if (mode !== 7) { // 忽略相位不显示
            list.push(obj)
          }
        }
        this.patternInfo.push(list)
      }
    },
    handleOverViewChange (val) {
      if (val === null || val.length === 0) return
      let valSplit = val.map(item => {
        return item.map(val => {
          return val.value + (val.sum ? val.sum : 0)
        })
      })
      let splitCycle = valSplit.length > 0 ? valSplit.map(item => {
        return item.length > 0 ? item.reduce((a, b) => {
          return a + b
        }) : 0
      }) : 0
      let cycle = Math.max(...splitCycle)// 每个环的周期最大值
      this.contrloCycle = cycle
      // 按环序分组
      let ringlength = []
      let ringsequence = val.map(item => {
        if (item.length === 0) return
        ringlength.push(item.length)
        return item.map(k => {
          return k.id
        })
      })
      let newRings = ringsequence.filter(item => item)
      let minLength = Math.min(...ringlength)
      let resultArrs = [] // 环1分组
      let resultArr = [] // 环2分组
      for (let j = 0; j < ringsequence[0].length; j += minLength) {
        resultArrs.push(ringsequence[0].slice(j, j + minLength))
        if (ringsequence[0].length === minLength) {
          resultArrs.push([])
        }
      }
      if (newRings.length > 1) {
        for (let i = 0; i < ringsequence[1].length; i += minLength) {
          resultArr.push(ringsequence[1].slice(i, i + minLength))
        }
      }
      this.patternInfo = []
      let currentArr = []
      let newPattern = []
      val.map(i => {
        newPattern.push(...i)
      })
      if (this.phaseList.length === 0) return
      for (let patternStatus of val[0]) {
        // if (patternStatus.mode !== 7) {
        let concurrent = this.phaseList.filter((item) => {
          return item.id === patternStatus.id // patternStatus.id当前相位id concurrent当前相位的并发相位
        })[0].concurrent// 当前相位的并发相位
        if (concurrent) {
          let obj = {
            id: patternStatus.id,
            current: concurrent.sort()
          }
          currentArr.push(obj)
        }
        // }
      }
      if (currentArr.length !== 0) {
        let newCurrent = this.tranform(currentArr)
        // 取没个环与环关系的并集
        let barrierRing1 = []
        let barrierRing2 = []
        let ring1 = [] // 环1与关系1的并集
        for (let h = 0; h < newCurrent.length; h++) {
          let adds = [...new Set(resultArrs[0])].filter(item => newCurrent[h].includes(item))
          ring1.push(adds)
        }
        let ring1s = [] // 环1与关系2的并集
        for (let h = 0; h < newCurrent.length; h++) {
          let addRing1 = [...new Set(resultArrs[1])].filter(item => newCurrent[h].includes(item))
          ring1s.push(addRing1)
        }
        barrierRing1.push(...ring1, ...ring1s)
        let resultList = []
        if (newRings.length > 1) {
          let ring2s = [] // 环2与关系1的并集
          for (let h = 0; h < newCurrent.length; h++) {
            let addRing2 = [...new Set(resultArr[1])].filter(item => newCurrent[h].includes(item))
            ring2s.push(addRing2)
          }
          let ring2 = [] // 环2与关系1的并集
          for (let h = 0; h < newCurrent.length; h++) {
            let add = [...new Set(resultArr[0])].filter(item => newCurrent[h].includes(item))
            ring2.push(add)
          }
          barrierRing2.push(...ring2, ...ring2s)
          for (let k = 0; k < barrierRing1.length; k++) {
            resultList.push(barrierRing1[k].concat(barrierRing2[k]))
          }
        }
        let resultLists = resultList.filter(item => item.length !== 0)
        let ringArr = []
        for (let l = 0; l < resultLists.length; l++) {
          for (let d = 0; d < newCurrent.length; d++) {
            if (newCurrent[d].filter(item => resultLists[l].includes(item)).length > 0) {
              ringArr.push({
                data: resultLists[l],
                id: d + 1,
                index: l
              })
            }
          }
        }
        for (var i = 0; i < ringArr.length; i++) {
          for (var j = i + 1; j < ringArr.length; j++) {
            if (ringArr[i].id === ringArr[j].id && ringArr[i].index + 1 === ringArr[j].index) {
              ringArr[i].data = ringArr[i].data.concat(ringArr[j].data)
              ringArr.splice(ringArr.indexOf(ringArr[j].id), 1)
            }
          }
        }
        let resArr = ringArr.map(item => item.data)
        let ringTeam = this.step1(this.phaseList, resArr)
        let ringTeams = ringTeam.filter(item => item.length !== 0)
        this.fillGap(ringTeams, val)
      }
      // let cycle = this.controlData.cycle
      for (let rings of val) {
        if (rings.length === 0) continue
        let list = []
        for (let ring of rings) {
          if (ring.value === 0) continue
          let obj = {}
          let split = ring.value
          obj.id = ring.id
          obj.mode = ring.mode
          // obj.split = split
          let currPhase = this.phaseList.filter((item) => {
            if (item.id === ring.id && item.controltype === 99) {
              obj.controltype = item.controltype
            }
            return item.id === ring.id
          })[0]
          if (!currPhase) return
          let peddirections = []
          for (let walk of this.sidewalkPhaseData) {
            if (currPhase.peddirection) {
              for (let ped of currPhase.peddirection) {
                // if (stg === walk.phaseid) {
                let objs = {}
                objs.name = walk.name
                objs.id = walk.id
                if (ped === walk.id) {
                  peddirections.push(objs)
                  peddirections = Array.from(new Set(peddirections))
                }
                // }
              }
            } else {
              peddirections = []
            }
          }
          if (ring.desc) {
            obj.direction = ring.desc.map(item => { // 虚相位desc为空
              return {
                id: item.id,
                color: '#454545'
              }
            })
          } else {
            if (currPhase.direction && currPhase.direction.length > 0) {
              obj.direction = currPhase.direction.map(item => {
                return {
                  id: item,
                  peddirection: peddirections,
                  color: '#454545'
                }
              })
            } else {
              obj.direction = [
                {
                  id: '',
                  color: '#454545',
                  peddirection: peddirections
                }
              ]
            }
          }
          obj.split = split
          obj.cycle = cycle
          if (ring.sum) {
            obj.sum = ring.sum
            obj.redWidth = ((currPhase.redclear + ring.sum) / (this.max ? this.max : cycle) * 100) + '%'
          } else {
            obj.redWidth = (currPhase.redclear / (this.max ? this.max : cycle) * 100) + '%'
          }
          obj.flashgreen = (currPhase.flashgreen / (this.max ? this.max : cycle) * 100) + '%'
          obj.yellowWidth = (currPhase.yellow / (this.max ? this.max : cycle) * 100) + '%'
          obj.greenWidth = ((split - currPhase.redclear - currPhase.yellow - currPhase.flashgreen) / (this.max ? this.max : cycle) * 100) + '%'
          // 忽略相位不显示
          // if (mode !== 7) { // 忽略相位不显示
          list.push(obj)
          // }
        }
        this.patternInfo.push(list)
      }
    },
    handleCurrentChange (val) { // 两个ring的数据
      if (val === null || val.length === 0) return
      // 按环序分组
      let ringlength = []
      let ringsequence = val.map(item => {
        if (item.length === 0) return
        ringlength.push(item.length)
        return item.map(k => {
          return k.id
        })
      })
      let newRings = ringsequence.filter(item => item)
      let minLength = Math.min(...ringlength)
      let resultArrs = [] // 环1分组
      let resultArr = [] // 环2分组
      for (let j = 0; j < ringsequence[0].length; j += minLength) {
        resultArrs.push(ringsequence[0].slice(j, j + minLength))
        if (ringsequence[0].length === minLength) {
          resultArrs.push([])
        }
      }
      if (newRings.length > 1) {
        for (let i = 0; i < ringsequence[1].length; i += minLength) {
          resultArr.push(ringsequence[1].slice(i, i + minLength))
        }
      }
      this.patternInfo = []
      this.barrierList = []
      let currentArr = []
      let newPattern = []
      val.map(i => {
        newPattern.push(...i)
      })
      if (this.phaseList.length === 0) return
      for (let patternStatus of val[0]) {
        // if (patternStatus.mode !== 7) {
        let concurrent = this.phaseList.filter((item) => {
          return item.id === patternStatus.id // patternStatus.id当前相位id concurrent当前相位的并发相位
        })[0].concurrent// 当前相位的并发相位
        if (concurrent) {
          let obj = {
            id: patternStatus.id,
            current: concurrent.sort()
          }
          currentArr.push(obj)
        }
        // }
      }
      if (currentArr.length !== 0) {
        let newCurrent = this.tranform(currentArr)
        // 取没个环与环关系的并集
        let barrierRing1 = []
        let barrierRing2 = []
        let ring1 = [] // 环1与关系1的并集
        for (let h = 0; h < newCurrent.length; h++) {
          let adds = [...new Set(resultArrs[0])].filter(item => newCurrent[h].includes(item))
          ring1.push(adds)
        }
        let ring1s = [] // 环1与关系2的并集
        for (let h = 0; h < newCurrent.length; h++) {
          let addRing1 = [...new Set(resultArrs[1])].filter(item => newCurrent[h].includes(item))
          ring1s.push(addRing1)
        }
        barrierRing1.push(...ring1, ...ring1s)
        let resultList = []
        if (newRings.length > 1) {
          let ring2s = [] // 环2与关系1的并集
          for (let h = 0; h < newCurrent.length; h++) {
            let addRing2 = [...new Set(resultArr[1])].filter(item => newCurrent[h].includes(item))
            ring2s.push(addRing2)
          }
          let ring2 = [] // 环2与关系1的并集
          for (let h = 0; h < newCurrent.length; h++) {
            let add = [...new Set(resultArr[0])].filter(item => newCurrent[h].includes(item))
            ring2.push(add)
          }
          barrierRing2.push(...ring2, ...ring2s)
          for (let k = 0; k < barrierRing1.length; k++) {
            resultList.push(barrierRing1[k].concat(barrierRing2[k]))
          }
        }
        let resultLists = resultList.filter(item => item.length !== 0)
        let ringArr = []
        for (let l = 0; l < resultLists.length; l++) {
          for (let d = 0; d < newCurrent.length; d++) {
            if (newCurrent[d].filter(item => resultLists[l].includes(item)).length > 0) {
              ringArr.push({
                data: resultLists[l],
                id: d + 1,
                index: l
              })
            }
          }
        }
        // let ringObj = {}
        // ringArr.forEach(item => {
        //   ringObj[item.index] = {
        //     id: item.id,
        //     index: item.index
        //   }
        // })
        for (var i = 0; i < ringArr.length; i++) {
          for (var j = i + 1; j < ringArr.length; j++) {
            if (ringArr[i].id === ringArr[j].id && ringArr[i].index + 1 === ringArr[j].index) {
              ringArr[i].data = ringArr[i].data.concat(ringArr[j].data)
              ringArr.splice(ringArr.indexOf(ringArr[j].id), 1)
            }
          }
        }
        let resArr = ringArr.map(item => item.data)
        this.barrierArr = resArr
        let ringTeam = this.step1(this.phaseList, resArr)
        let ringTeams = ringTeam.filter(item => item.length !== 0)
        if (this.patternList) {
          this.setBarrier(ringTeams, val)
        }
        this.fillGap(ringTeams, val)
        if (this.cycleChange) {
          const globalParamModel = this.$store.getters.globalParamModel
          let pattern = globalParamModel.getParamsByType('patternList')
          const allCycle = pattern.map(item => item.cycle)
          let cycle = Math.max(...allCycle)
          this.max = cycle
        } else {
          this.max = ''
        }
        let barrier = this.step2(ringTeams, newPattern)
        let barrierLeft = barrier.map(item => item - 0.3)
        this.barrierList = barrierLeft.map(j => {
          return (j / (this.max ? this.max : this.newCycle) * 100) + '%'
        })
        // this.barrierList.unshift(0)
      }
      for (let rings of val) {
        if (rings.length === 0) continue
        let list = []
        for (let ring of rings) {
          if (ring.value === 0) continue
          let obj = {}
          let split = ring.value
          obj.id = ring.id
          // obj.split = split
          let currPhase = this.phaseList.filter((item) => {
            if (item.id === ring.id && item.controltype === 99) {
              obj.controltype = item.controltype
            }
            return item.id === ring.id
          })[0]
          if (!currPhase) return
          let peddirections = []
          for (let walk of this.sidewalkPhaseData) {
            if (currPhase.peddirection) {
              for (let ped of currPhase.peddirection) {
                // if (stg === walk.phaseid) {
                let objs = {}
                objs.name = walk.name
                objs.id = walk.id
                if (ped === walk.id) {
                  peddirections.push(objs)
                  peddirections = Array.from(new Set(peddirections))
                }
                // }
              }
            } else {
              peddirections = []
            }
          }
          if (ring.desc && ring.desc.length > 0) {
            obj.direction = ring.desc.map(item => { // 虚相位desc为空
              return {
                id: item.id,
                color: '#454545',
                peddirection: peddirections
              }
            })
          } else {
            if (currPhase.direction && currPhase.direction.length > 0) {
              obj.direction = currPhase.direction.map(item => {
                return {
                  id: item,
                  color: '#454545',
                  peddirection: peddirections
                }
              })
            } else {
              obj.direction = [
                {
                  id: '',
                  color: '#454545',
                  peddirection: peddirections
                }
              ]
            }
          }
          obj.split = split
          obj.cycle = this.max ? this.max : this.newCycle
          if (ring.sum) {
            obj.sum = ring.sum
            obj.redWidth = ((currPhase.redclear + ring.sum) / (this.max ? this.max : this.newCycle) * 100) + '%'
          } else {
            obj.redWidth = (currPhase.redclear / (this.max ? this.max : this.newCycle) * 100) + '%'
          }
          obj.mode = ring.mode
          obj.greenWidth = ((split - currPhase.redclear - currPhase.yellow - currPhase.flashgreen) / (this.max ? this.max : this.newCycle) * 100) + '%'
          obj.flashgreen = (currPhase.flashgreen / (this.max ? this.max : this.newCycle) * 100) + '%'
          obj.yellowWidth = (currPhase.yellow / (this.max ? this.max : this.newCycle) * 100) + '%'
          // 忽略相位不显示
          // let mode = ring.mode
          // if (mode !== 7) { // 忽略相位不显示
          list.push(obj)
          // }
        }
        this.patternInfo.push(list)
      }
    },
    setBarrier (ringTeam, val) { // 添加特征参数barrier
      this.patternList.map(item => {
        if (item.id === this.patternIds) {
          const patternObjs = {}
          val.forEach(l => {
            l.map(k => {
              patternObjs[k.id] = k.value
            })
          })
          let ret = ringTeam.map((y, index) => {
            if (!y || y.length === 0) return
            y.map(n => {
              n.length = n.data.length > 1 ? n.data.reduce((pre, cur) => pre + patternObjs[cur], 0) : patternObjs[n.data[0]]
            })
            return {
              barrier: index + 1,
              length: y[0].length,
              items: y.map(j => {
                return {
                  ring: j.ring,
                  data: j.data
                }
              })
            }
          })
          item.barriers = ret
        }
      })
    },
    tranform (arr) { // 分barrier
      let newMap = new Map()
      arr.forEach(({ id, current }) => {
        const find = newMap.get(current.join())
        if (find) newMap.get(current.join()).push(id)
        else newMap.set(current.join(), [id])
      })
      let ret = []
      newMap.forEach((value, key) => {
        ret.push(Array.from(new Set(key.split(',').map(Number).concat(value))))
      })
      const result = []
      for (const a of ret) {
        let merged = false
        for (const r of result) {
          if (this.check([...r], a)) {
            a.forEach(item => r.add(item))
            merged = true
          }
        }
        if (!merged) {
          result.push(new Set(a))
        }
        merged = false
      }
      return result.map(s => [...s])
    },
    check (arr1, arr2) {
      return arr1.some(a1 => arr2.some(a2 => a1 === a2))
    },
    step1 (list, arr) { // 各个环包含的相位
      const ret = []
      const listObj = {}
      list.forEach(l => {
        listObj[l.id] = l.ring
      })
      arr.forEach(a => {
        const retItem = []
        a.forEach(b => {
          if (listObj[b]) {
            const find = retItem.find(r => r.ring === listObj[b])
            if (find) find.data.push(b)
            else retItem.push({ ring: listObj[b], data: [b] })
          }
        })
        ret.push(retItem)
      })
      return ret
    },
    step2 (newArr, pattern) { // 不同环并发相位做比较
      let ret = []
      let max = 0
      const patternObj = {}
      pattern.forEach(l => {
        // if (l.mode !== 7) {
        patternObj[l.id] = l.value
        // }
      })
      let barrierCycle = newArr.map(item => {
        return Math.max.apply(Math, item.map(k => { return k.length }))
      })
      barrierCycle.forEach((b, index) => {
        if (index === 0) {
          ret.push(barrierCycle[index])
        } else {
          if (max) {
            max = barrierCycle[index] + max
          } else {
            max = barrierCycle[index] + barrierCycle[index - 1]
          }
          ret.push(max)
        }
      })
      return ret
    },
    fillGap (newArr, pattern) {
      this.newPatterns = []
      const patternObj = {}
      pattern.forEach(l => {
        l.map(k => {
          // if (k.mode !== 7) {
          patternObj[k.id] = k.value
          // }
        })
      })
      let newMax = []
      let newMin = []
      newArr.forEach((na, index) => {
        if (!na || na.length === 0) return
        na.map(n => {
          n.length = n.data.length > 1 ? n.data.reduce((pre, cur) => pre + patternObj[cur], 0) : patternObj[n.data[0]]
        })
        let maxNum = Math.max.apply(Math, na.map(item => { return item.length }))
        let minNum = Math.min.apply(Math, na.map(item => { return item.length }))
        newMax.push(maxNum)
        newMin.push(minNum)
        let newmaxNum = Math.max.apply(Math, newMax)// 每组最大值
        let newminNum = Math.min.apply(Math, newMin)
        this.newCycle = newmaxNum + newminNum
        if (newmaxNum === newminNum) {
          this.max = newmaxNum + newminNum
          pattern.map(d => {
            d.map(r => {
              if (r.sum) {
                delete r.sum
              }
            })
          })
        }
        if (maxNum === minNum) {
          na.map(n => {
            pattern.map(h => {
              h.map(d => {
                if (d.id === n.data[1] && d.sum) {
                  delete d.sum
                }
              })
            })
          })
        } else {
          na.map(n => {
            if (n.length === maxNum) {
              pattern.map(h => {
                h.map(d => {
                  if (n.data.length > 1) {
                    if (d.id === n.data[1]) {
                      delete d.sum
                    }
                  } else {
                    if (d.id === n.data[0]) {
                      delete d.sum
                    }
                  }
                })
              })
            }
          })
        }
        na.forEach((value, index, array) => {
          if (value.length !== maxNum) {
            let newNa = []
            newNa.push(value)
            newNa.forEach(m => {
              let sum = Number(maxNum - m.length)
              pattern.filter((i) => {
                i.map(j => {
                  if (m.data.length > 1) {
                    if (j.id === m.data[1]) {
                      j.sum = sum
                    }
                  } else {
                    if (j.id === m.data[0]) {
                      j.sum = sum
                    }
                  }
                })
              })
            })
          }
          let mapAdd = pattern.map(item => {
            return item.map(val => {
              return val.value + (val.sum ? val.sum : 0)
            })
          })
          let maxCycle = mapAdd.length > 0 ? mapAdd.map(item => {
            return item.length > 0 ? item.reduce((a, b) => {
              return a + b
            }) : 0
          }) : 0
          this.max = Math.max(...maxCycle)// 每个环的周期最大值
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.main-patternstatus {
  position: relative;
}
.ring-first {
  margin-top: 1px;
  width: 100%;
  height: 34px;
}
.direction {
  filter: brightness(70%);
}
.mask {
  background: rgb(242, 121, 121) !important;
}
.first-1 {
  float: left;
  // text-align: center;
}
</style>
